package com.gitee.slowcreator.http.parser.json;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.gitee.slowcreator.http.config.HttpContextManager;
import com.gitee.slowcreator.http.enhance.around.EnhanceAfter;
import com.gitee.slowcreator.http.params.ScParseResult;
import com.gitee.slowcreator.http.params.ScReturn;
import com.gitee.slowcreator.http.util.JacksonUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.Map;

/**
 * json 解析器
 * 只能用于对象
 *
 * @author zxw
 * @date 2023/1/5 下午9:44
 */
@Slf4j
public class JsonHttpReturnParser implements EnhanceAfter {

    @Override
    public ScReturn after(ScReturn scReturn) {

        byte[] data = scReturn.getData();
        ScParseResult parse;
        try {
            parse = parse(data);
        } catch (Exception e) {
            // data 为空下面一进入就正常返回了
            log.error("解析json数据异常，解析参数base64：{}, 异常信息:", Base64.encode(data), e);
            parse = new ScParseResult(false, null);
        }
        scReturn.setParseData(parse);
        return scReturn;
    }

    private ScParseResult parse(byte[] input) {

        if (ArrayUtil.isEmpty(input)) {
            return new ScParseResult(false, null);
        }

        JsonParseParams jsonParseParams = (JsonParseParams) HttpContextManager.get(JsonParseParams.contextKey);
        if (jsonParseParams == null) {
            log.error("json解析器所需参数为空！");
            return new ScParseResult(false, null);
        }

        String successParams = jsonParseParams.getSuccessParams();
        Object successStatus = jsonParseParams.getSuccessStatus();
        Type type = jsonParseParams.getType();

        if (StrUtil.isBlank(successParams) || successStatus == null || type == null) {
            return new ScParseResult(false, null, input);
        }

        Object data = JacksonUtil.parseObject(input, new TypeReference<Object>() {
            @Override
            public Type getType() {
                return type;
            }
        });

        Object status;
        if (data instanceof Map) {
            // 如果是map类型直接获取
            @SuppressWarnings("rawtypes")
            Map resultMap = (Map) data;
            status = resultMap.get(successParams);
        } else {
            // 其他类型通过反射获取
            status = ReflectUtil.getFieldValue(data, successParams);
        }

        if (status == null) {
            // 没有获取到状态值 返回失败
            return new ScParseResult(false, null, input);
        }

        boolean resultStatus;
        if (status instanceof Number && successStatus instanceof Number) {

            BigDecimal s1 = new BigDecimal(String.valueOf(status));
            BigDecimal s2 = new BigDecimal(String.valueOf(successStatus));

            resultStatus = s1.compareTo(s2) == 0;
        } else {
            resultStatus = status.equals(successStatus);
        }

        return new ScParseResult(resultStatus, data, null);
    }
}
